<?php
/**
 * @package panel
 * @subpackage panel.environment.db
 */
/**
 * Raw select object
 * @author Dmitry Bakaleinik (code)
 */
class panel__db__call
	extends maf__sqlgen__abstract {

	protected $call;
	protected $arguments = array();
	protected $escape    = array();
	protected $iud;

	/**
	 * @return panel__db__call
	 */
	static public function create() {

		return new self;

	}	# Function

	/**
	 * @return panel__db__call
	 */
	public function setEscape($_pos_, $_state_) {

		$this->escape[$_pos_] = $_state_;

		return $this;

	}	# Function

	/**
	 * @return panel__db__call
	 */
	public function setCall($_, $_iud_ = FALSE ) {

		$this->call = $_;
		$this->iud = $_iud_;

		return $this;

	}	# Function

	/**
	 * @return panel__db__call
	 */
	public function setArguments( array $_ ) {

		$this->arguments = $_;

		return $this;

	}	# Function

	public function getSQL() {

		$R  = "CALL ";
		$R .= mysql_escape_string($this->call);
		$R .= "(";

		$args = array();

		foreach( $this->arguments as $_pos => $_ ) {

			switch( TRUE ) {

			case is_string($_);

				if( isset_or($this->escape[$_pos + 1], TRUE) ) {

					$args[] = "'" . mysql_escape_string($_) . "'";

				} else {

					$args[] = $_;

				}	# if

				break;

			default:
				$args[] = $_;
				break;

			}	# switch

		}	# foreach

		$R .= implode(",", $args);

		$R .= ")";

		return $R;

	}	# Function

	public function execute() {

		try {

			if( !$this->iud ) {

				return p()->db()->querySelect($this->getSQL());

			} else {

				return p()->db()->queryIUD($this->getSQL());

			}	# if

		} catch ( PDOException $e ) {

			$e2 = new panel__e__exception(

				($message = p()->db()->getLastError()) ? $message :
				$e->getMessage()

			);

			$e2["trigger_exception"] = $e;

			panel__logger__errors::getInstance()->logException( $e2 );

			throw $e2;

		}	# try

	}	# Function

	public function extractValue() {

		$r = self::execute();
		$a = func_get_args();

		array_unshift($a, $r);

		return call_user_func_array( array("maf__helpers__array", "getElement"), $a );

	}	# Function

	public function extractColumn($_column_) {

		$r = self::execute();
		return maf__helpers__array::extractColumn($r, $_column_);

	}	# Function

	public function extractFirst() {

		$r = self::execute();
		return current($r);

	}	# Function

}	# Class

/* EOF */